<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="商品标题" prop="subject">
        <el-input v-model="queryParams.subject" placeholder="请输入商品标题" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="skuCode" prop="skuCode">
        <el-input clearable @keyup.enter.native="handleQuery" v-model="queryParams.skuCode" placeholder="skuCode搜索">
        </el-input>
      </el-form-item>
      <el-form-item label="产品Id" prop="collectProductId">
        <el-input v-model="queryParams.collectProductId" @keyup.enter.native="handleQuery" placeholder="产品Id搜索"
                  clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="商品属性" prop="isGeneral">
        <el-select v-model="queryParams.isGeneral" placeholder="请选择商品属性" clearable>
          <el-option v-for="dict in isGeneralList" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="类目" prop="categoryId">
        <treeselect style="width: 220px;" v-model="queryParams.categoryId" :options="categoryList"
                    :normalizer="normalizer" placeholder="请选择类目"/>
      </el-form-item>
      <el-form-item label="店铺账号" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="店铺账号" @change="queryStoreChange" clearable>
          <el-option v-for="dict in accountNumber" :key="dict.value" :label="dict.lable" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" prop="onShelf">
        <el-select v-model="queryParams.onShelf" placeholder="是否上架" @change="queryOnshelfChange" clearable>
          <el-option v-for="dict in shelfList" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="选择品牌" prop="brandId">
        <el-select v-model="queryParams.brandId" placeholder="请选择" clearable>
          <el-option v-for="dict in brandList" :key="dict.value" :label="dict.lable" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品标签" prop="classifyLabel">
        <el-select v-model="queryParams.classifyLabel" placeholder="请选择" clearable>
          <el-option v-for="dict in classifyList" :key="dict.value" :label="dict.lable" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-tabs type="border-card" @tab-click="handleTabClick">
      <el-tab-pane v-for="(item, index) in tabsList" :key="index" :label="item.label">
        <el-row :gutter="10" class="operation">
          <el-col :span="2" style="text-align: center">
            <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="onCheckAll">全选</el-checkbox>
          </el-col>
          <el-col :span="3" class="operation-item">
            <div @click="publishBtn">
              <i class="el-icon-upload2"></i>发布速卖通产品
            </div>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-view" size="mini" @click="handleView">查看刊登日志</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" size="mini" :disabled="multiple" @click="getProductShareCode">生成分享码
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini" @click="queryUseShareCode">使用分享码</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-view" plain size="mini" @click="openShareCodeModal">查看我的分享码
            </el-button>
          </el-col>
        </el-row>
        <div class="sellerproduct-list" v-loading="loading">
          <div class="sellerproduct-list-item" v-for="(item, index) in productList" :key="index">
            <el-card>
              <div>
                <div :style="{ padding: '10px' }">
                  <div class="pCheckbox">
                    <el-checkbox v-model="item.isChecked" @change="onItemChange($event, item)">
                      <img v-if="item.imageURLs" :src="item.imageURLs.split(',')[0]"
                           class="sellerproduct-list-item-image">
                    </el-checkbox>
                  </div>
                  <div class="sellerproduct-list-item-info" @click="openProductDrawer(item.id)">
                    <span class="info-price">{{ item.productPrice || '-' }}</span>
                    <div class="info-title">{{ item.subject || '-' }}</div>
                    <div class="info-brandName">
                      <el-tag v-if="item.brandName">品牌：{{ item.brandName }}</el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    :pageSizes="[18, 36, 54]" @pagination="getList"/>
      </el-tab-pane>
    </el-tabs>

    <!-- 速卖通产品上传 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <div class="form-box">
          <div class="form-box-header">产品属性替换</div>
          <div class="form-box-content">
            <el-form-item label="店铺账号" prop="storeId">
              <el-select v-model="form.storeId" placeholder="店铺账号" @change="storeChange" clearable filterable>
                <el-option v-for="dict in accountNumber" :key="dict.value" :label="dict.lable" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="审核中是否下架" prop="isAudit">
              <div class="item-flex-box">
                <div class="item-flex-box-radio">
                  <el-radio v-model="form.isAudit" label="1">是</el-radio>
                  <el-radio v-model="form.isAudit" label="0">否</el-radio>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="产品价格" prop="priceAdjustmentMethod">
              <div class="item-flex-box">
                <div class="item-flex-box-radio">
                  <el-radio v-model="form.priceAdjustmentMethod" label="0" @change="priceRadioChange">手动定价
                  </el-radio>
                  <el-radio v-model="form.priceAdjustmentMethod" label="1" @change="priceRadioChange">智能定价
                  </el-radio>
                </div>
                <div class="item-flex-box-input">
                  <div v-if="form.priceAdjustmentMethod == '0'" class="item-flex-box-input-i">
                    <span class="text">销售价格</span>
                    <el-select class="width-select-1" v-model="form.readjustPricesType">
                      <el-option v-for="dict in priceList" :key="dict.value" :label="dict.label" :value="dict.value"/>
                    </el-select>
                    <el-input class="width-input" v-model="form.readjustPrices" placeholder=""></el-input>
                    <span class="text">%</span>
                  </div>
                  <div v-else class="item-flex-box-input-i">
                    <el-select class="width-select-2" v-model="form.templateId" placeholder="---请选择智能定价模板---">
                      <el-option v-for="dict in priceTemplateList" :key="dict.value" :label="dict.lable"
                                 :value="dict.value"/>
                    </el-select>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="替换品牌" prop="brandId">
              <el-select v-model="form.brandId">
                <el-option v-for="dict in brandByIdList" :key="dict.attr_value_id" :label="dict.zhName"
                           :value="dict.attr_value_id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="替换库存" prop="skuStock">
              <el-input-number class="width-input" :min="0" step-strictly v-model="form.skuStock"
                               placeholder=""></el-input-number>
            </el-form-item>
            <el-form-item label="库存扣减策略" prop="reduceStrategy">
              <el-radio-group v-model="form.reduceStrategy">
                <el-radio v-for="dict in dict.type.erp_reduce_strategy" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="主图调序" prop="isMainImageReordering">
              <el-radio-group v-model="form.isMainImageReordering">
                <el-radio label="1">调序</el-radio>
                <el-radio label="2">不调序</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="添加图片水印" prop="isAddWatemark">
              <el-radio-group v-model="form.isAddWatemark">
                <el-radio label="0">不需要</el-radio>
                <el-radio label="1">需要</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="运费模板" prop="freightTemplateId"
                          :rules="isAutoMate ? [{ required: false}] : rules.freightTemplateId">
              <div class="item-flex-box widthBox">
                <el-select :disabled="isAutoMate" v-model="form.freightTemplateId" placeholder="---请选择运费模板---"
                           clearable>
                  <el-option v-for="dict in freightTemplateList" :key="dict.value" :label="dict.lable"
                             :value="dict.value*1"/>
                </el-select>
                <span class="text color" @click="freightTemplateSync">同步</span>
                <el-checkbox v-if="isRmb" v-model="isAutoMate">自动匹配运费模板</el-checkbox>
              </div>
            </el-form-item>
            <el-form-item label="服务模板" prop="promiseTemplateId">
              <div class="item-flex-box widthBox">
                <el-select v-model="form.promiseTemplateId" placeholder="---请选择服务模板---" clearable>
                  <el-option v-for="dict in serviceTemplateList" :key="dict.value" :label="dict.lable"
                             :value="dict.value*1"/>
                </el-select>
                <span class="text color" @click="serviceTemplateSync">同步</span>
              </div>
            </el-form-item>
            <el-form-item label="营销方案" prop="activityId">
              <div class="item-flex-box widthBox">
                <el-select v-model="form.activityId" placeholder="---请选择营销方案---" clearable filterable>
                  <el-option v-for="dict in marketList" :key="dict.activityId" :label="dict.label"
                             :value="dict.activityId"/>
                </el-select>
                <span class="text color" @click="marketSync">同步</span>
              </div>
            </el-form-item>
            <el-form-item label="商品分组" prop="groupId">
              <div class="item-flex-box widthBox">
                <el-select v-model="form.groupId" placeholder="---请选择商品分组---" clearable filterable>
                  <el-option v-for="(dict,index) in groupList" :key="index" :label="dict.groupName"
                             :value="dict.groupId"/>
                </el-select>
                <span class="text color" @click="asyncGroupList">同步</span>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="addSellerStoreProductBtn">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品详情 -->
    <el-drawer title="编辑" :visible.sync="drawer" direction="rtl" size="48%" :before-close="handleClose"
               custom-class="demo-drawer" destroy-on-close ref="drawer">
      <div class="demo-drawer__content">
        <el-form :model="detailsForm" ref="detailsForm" :rules="detailsRules" :inline="true" label-width="100px">
          <el-row>
            <div>
              <el-col :span="24">
                <div class="title">基本信息</div>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品属性" prop="productAttribute">
                  <el-select disabled v-model="detailsForm.expand.productAttribute">
                    <el-option v-for="dict in dict.type.erp_product_attribute" :key="dict.value" :label="dict.label"
                               :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品类目" prop="categoryId">
                  <el-cascader v-model="detailsForm.categoryId" :options="categoryList"
                               :props="{ value: 'id', label: 'name', checkStrictly: true }" disabled></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品单位" prop="productUnit">
                  <el-select v-model="detailsForm.productUnit" disabled>
                    <el-option v-for="dict in dict.type.ae_product_unit" :key="dict.value" :label="dict.label"
                               :value="dict.value*1"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="品牌选择" prop="brandId">
                  <el-select disabled v-model="detailsForm.expand.brandId">
                    <el-option v-for="dict in brandList" :key="dict.value" :label="dict.lable" :value="dict.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col v-if="newClassifyList.length > 0" :span="24">
                <el-form-item class="flexbox" label="商品标签" prop="classifyLabel">
                  <div class="border-box">
                    <el-tag v-for="(tag) in newClassifyList" :key="tag.value">{{ tag.lable }}</el-tag>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品主图" prop="imageURLs">
                  <div class="border-box">
                    <image-upload ref="uploadImage" key="file-upload-image" v-model="detailsForm.imageURLs"
                                  :fileSize="3" :isAi="detailsForm.expand.isOptimize==1?true:false"
                                  :product-id="detailsForm.id" :isShowTip="false" :limit="6"/>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="白底图" prop="white">
                  <image-upload ref="uploadWhite" key="file-upload-white" v-model="detailsForm.white" :fileSize="3"
                                :limit="1" isLimitsize/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="营销图" prop="marketing">
                  <image-upload ref="uploadMarketing" key="file-upload-marketing" v-model="detailsForm.marketing"
                                :product-id="detailsForm.id" :fileSize="3" :limit="1"
                                :isAi="detailsForm.expand.isOptimize==1?true:false" isLimitsize/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品视频" prop="media">
                  <file-upload ref="uploadVideo" key="file-upload-video" :fileType="['mp4']" v-model="detailsForm.media"
                               :limit="1"/>
                </el-form-item>
              </el-col>
              <el-col v-if="Array.isArray(detailsForm.customAttributes)" :span="24">
                <el-form-item class="flexbox" label="产品属性" prop="">
                  <div class="border-box">
                    <el-form-item v-for="(item, index) in detailsForm.customAttributes" :key="index" class="flexbox"
                                  :label="item.zhName" label-width="240px">
                      <div class="box-input-item">
                        <el-input v-if="item.attributeShowTypeValue == 'input'" v-model.trim="item.attr_value"
                                  placeholder="请输入" disabled/>
                        <el-select v-if="item.attributeShowTypeValue == 'list_box'" v-model="item.attr_value_id"
                                   disabled>
                          <el-option v-for="(jDict, j) in item.values" :key="j" :label="jDict.zhName"
                                     :value="jDict.attr_value_id"/>
                        </el-select>
                        <el-select v-if="item.attributeShowTypeValue == 'check_box'" multiple
                                   v-model="item.attr_value_id" disabled>
                          <el-option v-for="(dict, i) in item.values" :key="i" :label="dict.zhName"
                                     :value="dict.attr_value_id"/>
                        </el-select>
                      </div>
                    </el-form-item>
                  </div>
                </el-form-item>
              </el-col>
            </div>
            <div>
              <el-col :span="24">
                <div class="title">规格库存</div>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品规格" prop="">
                  <div class="border-box">
                    <div class="tagBox">
                      <div v-for="(item) in JSON.parse(detailsForm.expand.skuProperty || '[]')" :key="item.value"
                           class="tagBox-item">
                        <div class="tagBox-item-name">
                          <span class="name-text">{{ item.name }}</span>
                        </div>
                        <div class="tagBox-item-list">
                          <template v-if="item.list.length > 0">
                            <el-tag v-for="(tag) in item.list" :key="tag.value">{{ tag.name }}</el-tag>
                          </template>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div class="paddingLeft-box">
                  <el-table :data="newSkuList" border :header-cell-style="{'text-align':'center'}"
                            :cell-style="{'text-align':'center'}" header-cell-class-name="table-header" width="100%"
                            current-row-key="uid" row-class-name="table-row">
                    <template v-if="detailsForm.expand">
                      <el-table-column v-for="(leftTitle) in JSON.parse(detailsForm.expand.skuProperty || '[]')"
                                       :key="leftTitle.value" :label="leftTitle.name" fixed>
                        <template slot-scope="scope">{{
                            propertyLabel(scope.row.skuPropertyIds, leftTitle.value)
                          }}
                        </template>
                      </el-table-column>
                    </template>
                    <el-table-column prop="skuImage" label="sku图片" width="120">
                      <template slot-scope="scope">
                        <el-form-item>
                          <image-preview :src="scope.row.skuImage" :width="80" :height="80"/>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="skuCode" label="skuCode"/>
                    <el-table-column prop="skuStock" label="sku库存">
                      <template slot-scope="scope">
                        <el-form-item>
                          <el-input disabled v-model="scope.row.skuStock"></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
              <el-col v-if="checkedCities.length > 0" :span="24">
                <el-form-item class="flexbox" label="区域定价" prop="">
                  <div class="border-box">
                    <div class="tagBox">
                      <div class="tagBox-item">
                        <div class="tagBox-item-list">
                          <el-tag v-for="tag in checkedCities" :key="tag.lable" :disable-transitions="false">
                            {{ tag.value }}[{{ tag.lable }}]
                          </el-tag>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col v-if="checkedCities.length > 0" :span="24">
                <div class="paddingLeft-box">
                  <el-table :data="newAreaList" border :header-cell-style="{'text-align':'center'}"
                            :cell-style="{'text-align':'center'}" header-cell-class-name="table-header" width="100%"
                            current-row-key="uid" row-class-name="table-row">
                    <template v-if="detailsForm.expand">
                      <el-table-column v-for="(leftTitle) in JSON.parse(detailsForm.expand.skuProperty || '[]')"
                                       :key="leftTitle.value" :label="leftTitle.name" fixed>
                        <template slot-scope="scope">
                          {{propertyLabel(scope.row.skuPropertyIds, leftTitle.value)}}
                        </template>
                      </el-table-column>
                    </template>
                    <el-table-column v-for="(leftTitle) in absoluteQuoteMap" :key="leftTitle.shiptoCountry"
                                     :label="leftTitle.shiptoCountry" width="100">
                      <template slot-scope="scope">
                        <el-form-item :prop="absoluteQuoteMapProp(scope.row, leftTitle)">
                          <el-input disabled :value="absoluteQuoteMapValue(scope.row, leftTitle)"/>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
            </div>
            <div>
              <el-col :span="24">
                <div class="title">商品详情</div>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品标题" prop="subject">
                  <el-input v-model="detailsForm.subject" placeholder="请输入商品名称" maxlength="128" clearable/>
                  <el-button type="text" @click="createTitleBtn" :loading="createTitleLoading">AI生成标题</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品详情" prop="detail">
                  <el-input v-model="detailsForm.detail" type="textarea" :autosize="{ minRows: 2, maxRows: 12}"
                            placeholder="请输入商品详情" clearable/>
                  <el-button @click="createProductDescriptionBtn" :loading="createProductLoading" type="text">
                    根据详情关键词生成详情
                  </el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="flexbox" label="商品详情图" prop="detailImg">
                  <div class="border-box">
                    <image-upload ref="uploadDetailsImage" key="file-upload-detailsimage"
                                  v-model="detailsForm.detailImg" :fileSize="3"
                                  :isAi="detailsForm.expand.isOptimize==1?true:false" :product-id="detailsForm.id"
                                  :isShowTip="false" :limit="99"/>
                  </div>
                </el-form-item>
              </el-col>
            </div>
          </el-row>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="drawer = false;">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="buttonLoading">
            {{ buttonLoading ? '提交中 ...' : '提 交' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog title="刊登日志" :visible.sync="isShowOrderLog" width="70%">
      <div class="edit-box">
        <el-tabs v-model="tabsIndex" type="card" @tab-click="handleClick">
          <el-button type="primary" @click="getOrderList" icon="el-icon-refresh" size="mini">刷新</el-button>
          <el-tab-pane v-for="(tabItem, tabIndex) in tabList" :key="tabIndex" :label="tabItem.label"
                       :name="tabItem.name">
            <el-table :data="orderLogList" align="center" v-loading="orderLoading" style="width: 100%" border>
              <el-table-column prop="subject" align="center" show-overflow-tooltip label="产品名称"></el-table-column>
              <el-table-column prop="collectProductId" align="center" label="产品Id"></el-table-column>
              <el-table-column label="商品图" align="center" prop="imageURLs" width="100">
                <template slot-scope="scope">
                  <imagePreview :src="(scope.row.imageURLs || '').split(';')[0]" width="60px" height="60px"/>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="刊登状态" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.status == 1 ? '刊登中' : scope.row.status == 2 ? '刊登成功' : '刊登失败' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="publishDate" label="刊登时间" align="center"></el-table-column>
              <el-table-column prop="remark" label="备注" align="center"></el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <pagination v-show="orderTotal>0" :total="orderTotal" :page.sync="orderParams.pageNum"
                    :limit.sync="orderParams.pageSize" :pageSizes="[10, 20, 40]" @pagination="getOrderList"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowOrderLog = false">取 消</el-button>
      </span>
    </el-dialog>
    <!--  分享码弹窗组件  -->
    <ShareCodeList v-if="isOpenShareCodeModal" :list="shareCodeList"
                   @closeShareCodeModal="closeShareCodeModal"/>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ShareCodeList from "@/views/product/components/ShareCodeList.vue";
import {
  listSellerProduct,
  getSellerProduct,
  delSellerProduct,
  updateSellerProduct,
  listsellerFreightTemplate,
  listsellerPromiseTemplate,
  listSellerStorePriceTemplate,
  syncListsellerFreightTemplate,
  syncListsellerPromiseTemplate,
  addSellerStoreProduct,
  brandList,
  myPublishingList,
  storeActivityList,
  selectStorePromotionsTemplate,
  isRmb, queryAvailableGroupsByStoreId, queryStoreGroupList
} from "@/api/product/personal/index";
import {queryUserShopList} from "@/api/shop/index"
import {
  getSelect,
  getArea,
  getBrand,
  categoryInfo,
  createTitle,
  createProductDescription
} from "@/api/attribute/index";
import {selectAlreadyList} from "@/api/gather/collectProductCategory";
import uuid from '@/utils/uuid'
import store from '@/store'
import {queryshareCodeList, useShareCode, sellerProductShare} from "@/api/seller/shopDecoration";

export default {
  components: {
    Treeselect,
    ShareCodeList
  },
  name: "SellerProduct",
  dicts: ['ae_product_unit', 'erp_product_attribute', 'erp_reduce_strategy', 'erp_product_template'],
  data() {
    return {
      arrayStoreActivity: [],//店铺可用营销方案列表
      // 按钮loading
      buttonLoading: false,
      createProductLoading: false,//生成详情loading
      createTitleLoading: false,//生成标题loading
      // 遮罩层
      loading: true,
      orderLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      orderTotal: 0,
      // 卖家商品
      sellerProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 18,
        subject: undefined,
        isGeneral: undefined,
        skuCode: undefined,
        collectProductId: undefined,
        categoryId: undefined,
        storeId: undefined,
        onShelf: undefined,
        brandId: undefined,
        templateId: undefined
      },
      orderParams: {
        pageNum: 1,
        pageSize: 10,
        status: 1
      },
      // 发布速卖通表单参数
      form: {
        'priceAdjustmentMethod': '0',
        'readjustPricesType': '1',
        'readjustPrices': undefined,
        'templateId': undefined,
        'activityId': undefined,
        'isAutoMate': '0',
        'isAudit': '1',
        reduceStrategy: '1'
      },
      // 发布速卖通表单校验
      rules: {
        storeId: [
          {required: true, message: "必填项不能为空", trigger: ['blur', 'change']}
        ],
        isAudit: [
          {required: true, message: "必填项不能为空", trigger: ['blur', 'change']}
        ],
        priceAdjustmentMethod: [
          {required: true, message: "必填项不能为空", trigger: ['blur', 'change']}
        ],
        brandId: [
          {required: true, message: "必填项不能为空", trigger: ['blur', 'change']}
        ],
        skuStock: [{required: false, message: "必填项不能为空", trigger: ['blur']}],
        reduceStrategy: [
          {required: true, message: "必填项不能为空", trigger: ['blur']}
        ],
        isMainImageReordering: [{required: true, message: "不能为空", trigger: ['change']}],
        isAddWatemark: [{required: true, message: "不能为空", trigger: ['change']}],
        freightTemplateId: [
          {required: true, message: "必填项不能为空", trigger: ['blur']}
        ],
        activityId: [{required: true, message: "营销模板不能为空", trigger: ['change']}],
        promiseTemplateId: [{required: true, message: "必填项不能为空", trigger: ['blur']}]
      },
      isCheckAll: false, // 全选
      // 全选
      isIndeterminate: false,
      accountNumber: [], // 店铺账号
      shelfList: [
        {
          value: '0',
          label: '上架'
        },
        {
          value: '1',
          label: '未上架'
        }
      ],
      priceList: [
        {
          value: '0',
          label: '减去'
        },
        {
          value: '1',
          label: '加上'
        }
      ],
      isGeneralList: [
        {
          value: '0',
          label: '普货'
        },
        {
          value: '1',
          label: '特货'
        }
      ],
      drawer: false, // 商品详情弹框
      productId: null, // 商品id
      detailsForm: {
        'expand': {
          'brandId': null,
          'skuProperty': '[]',
          'productAttribute': null
        }
      },
      detailsRules: {},
      categoryList: [], // 类目列表
      brandList: [], // 品牌列表
      classifyList: [], // 全部标签列表
      newClassifyList: [],
      customAttributes: [], // 属性值
      areaList: [], // 全部区域列表
      freightTemplateList: [], // 运费模板列表
      serviceTemplateList: [], // 服务模板列表
      marketList: [], // 营销方案列表
      brandByIdList: [],
      proArr: [],
      priceTemplateList: [], // 智能定价模板列表
      isShowOrderLog: false, // 刊登日志弹框
      orderLogList: [], // 刊登日志
      tabList: [
        {
          name: '1',
          label: '刊登中'
        },
        {
          name: '2',
          label: '刊登成功'
        }, {
          name: '3',
          label: '刊登失败'
        }
      ],
      tabsIndex: '1',
      isRmb: false,
      isAutoMate: false,
      isOpenShareCodeModal: false,//是否打开分享码列表
      shareCodeList: [],//分享码列表
      groupList: [],//商品分组列表
    };
  },
  computed: {
    tabsList() {
      return [{value: '', label: '全部'}, ...this.dict.type.erp_product_template]
    },
    productList() {
      let productList = this.sellerProductList;
      productList.forEach((item) => {
        const imageURLsArr = (item.imageURLs || '').split(';').filter(i => !!i)
        const newArr = []
        imageURLsArr.forEach(val => {
          if (val.indexOf('http://') === -1 && val.indexOf('https://') === -1) {
            newArr.push(store.getters.domain + val)
          } else {
            newArr.push(val)
          }
        })
        item.imageURLs = newArr.toString();
        this.$set(item, "isChecked", false);
      });
      return productList;
    },
    // sku商品
    propertyLabel() {
      if (this.detailsForm.expand) {
        const ls = JSON.parse(this.detailsForm.expand.skuProperty || '[]')
        return (ids, val) => {
          try {
            const items = ids
              .split(';').filter(item => !!item && new RegExp(`^${val}:[0-9]+`).test(item))
              .map(it => {
                const [p1, p2] = it.split(':').filter(item => !!item)
                return ls.filter(item => item.value == p1)[0].list.filter(item => item.value == p2)[0]
              })
            return items[0].name
          } catch (e) {
            return '-'
          }
        }
      } else return '-'
    },
    // sku列表数据
    newSkuList() {
      if (this.detailsForm.expand) {
        const skuProperty = JSON.parse(this.detailsForm.expand.skuProperty || '[]')
        const idsArr = []
        skuProperty.forEach((p1, p1Index) => {
          (p1.list || []).forEach((p2, p2Index) => {
            if (!idsArr[p1Index]) idsArr.push([])
            idsArr[p1Index].push(`${p1.value}:${p2.value}`)
          })
        })
        const skuPropertyIdsArr = skuPropertyPackage(idsArr, 0)
        const list = skuPropertyIdsArr.map(ids => {
          const rowData = this.getRowData(ids)
          return rowData
        })
        return list
      } else return []
    },
    // 区域定价数据
    absoluteQuoteMap: {
      get() {
        if (this.detailsForm.expand) {
          return JSON.parse(this.detailsForm.expand.absoluteQuoteMap || '[]')
        } else {
          return []
        }
      },
      set(val) {
        if (this.detailsForm.expand) {
          this.$set(this.detailsForm.expand, 'absoluteQuoteMap', JSON.stringify(val || []))
        } else {
          this.detailsForm.expand = {
            absoluteQuoteMap: JSON.stringify(val || [])
          }
        }
      }
    },
    // 区域定价的国家数据
    checkedCities() {
      const selectCountrys = this.absoluteQuoteMap.map(item => item.shiptoCountry)
      return this.areaList.filter(item => selectCountrys.includes(item.lable))
    },
    // 区域列表数据
    newAreaList() {
      return this.newSkuList.map(sku => ({
        ...sku,
      }))
    },
    // 区域定价，输入框 value
    absoluteQuoteMapValue() {
      return (row, column) => {
        const value = (column.absoluteQuoteMap || {})[row.skuPropertyIds.replace(/\,/g, ';')] || '0'
        // debugger
        return value
      }
    },
    absoluteQuoteMapProp() {
      return (row, column) => {
        const prop = encodeURIComponent(`absoluteQuoteMap_${column.shiptoCountry}_${row.skuPropertyIds}`)
        // console.log(prop)
        return prop
      }
    }
  },
  created() {
    this.getList();
    this.getGoodsCategory();
    this.getBrandList();
    this.getSelectList();
    this.getAreaList();
    this.getEmpowerList();
    this.getPriceTemplateList();
  },
  methods: {
    handleTabClick(el) {
      this.queryParams.templateId = this.tabsList[el.index].value;
      this.getList();
    },
    // 自动生成标题
    createTitleBtn() {
      console.log('this.detailsForm', this.detailsForm)
      var keyword = this.detailsForm.expand.keyword;
      if (keyword) {
        this.createTitleLoading = true;
        createTitle({'words': keyword}).then(res => {
          if (res.code === 200) {
            this.detailsForm.subject = res.data;
            this.createTitleLoading = false;
            this.$modal.msgSuccess("生成成功！");
          } else {
            this.createTitleLoading = false;
            this.$modal.msgError("生成失败！");
          }
        }).catch(() => {
          this.createTitleLoading = false;
        })
      } else {
        this.$modal.msgError("生成失败！");
      }
    },
    // 根据详情关键词生成详情
    createProductDescriptionBtn() {
      var keyword = this.detailsForm.expand.detailKeyword;
      if (keyword) {
        this.createProductLoading = true;
        createProductDescription({'words': keyword}).then(res => {
          if (res.code === 200) {
            this.detailsForm.detail = res.data;
            this.createProductLoading = false;
            this.$modal.msgSuccess("生成成功！");
          } else {
            this.createProductLoading = false;
            this.$modal.msgError("生成失败！");
          }
        }).catch(() => {
          this.createProductLoading = false;
        })
      } else {
        this.$modal.msgError("生成失败！");
      }
    },
    // 产品价格切换
    priceRadioChange() {
      this.form.readjustPricesType = '1';
      this.form.readjustPrices = undefined;
      this.form.templateId = undefined;
    },
    /** 查询卖家商品 */
    getList() {
      this.loading = true;
      this.isCheckAll = false;
      listSellerProduct(this.queryParams).then(response => {
        this.sellerProductList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 选择店铺
    storeChange(e) {
      this.freightTemplateList = [];
      this.serviceTemplateList = [];
      this.marketList = [];
      this.brandByIdList = [];
      this.form.freightTemplateId = '';
      this.form.promiseTemplateId = '';
      this.form.activityId = '';
      if (e) {
        this.getFreightTemplateList(e);//获取运费模板
        this.getPromiseTemplateList(e);//获取服务模板
        this.getStoreActivityList(e);//获取营销列表
        this.getBrandById(e);
        this.getIsRmb(e); // 判断是否为人民币
        this.getGroupList(e)
      }
    },
    // 获取商品分组列表
    getGroupList(e) {
      queryAvailableGroupsByStoreId({storeId: e}).then(res => {
        this.groupList = res.data
      })
    },
    // 同步商品分组
    asyncGroupList() {
      this.$confirm('是否确定同步店铺内商品分组？').then(() => {
        if (this.form.storeId) {
          this.loading = true;
          queryStoreGroupList({storeId: this.form.storeId}).then(res => {
            this.$modal.msgSuccess("同步成功");
            this.getGroupList(this.form.storeId);//获取店铺分组列表
            this.marketList = res.data
            this.loading = false;
          });
        } else {
          this.$modal.msgError("请选择店铺账号");
        }
      })
    },
    queryStoreChange(e) {
      this.queryParams.onShelf = undefined;
    },
    // 是否上架
    queryOnshelfChange(e) {
      if (!this.queryParams.storeId) {
        this.$message({
          message: '请先选择店铺',
          type: 'warning'
        });
        this.queryParams.onShelf = undefined;
      }
    },
    /** 转换类目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 商品类目
    getGoodsCategory() {
      selectAlreadyList().then(response => {
        this.categoryList = this.handleTree(response.data, "id", "parentId");
      });
    },
    // 获取品牌选择列表
    getBrandList() {
      getBrand().then(res => {
        this.brandList = res.data
      });
    },
    // 获取智能定价模板
    getPriceTemplateList() {
      listSellerStorePriceTemplate().then(res => {
        this.priceTemplateList = res.data
      });
    },
    // 根据类目id和商家id获取有权限品牌
    getBrandById(id) {
      const params = {
        categoryId: this.proArr[0].categoryId,
        storeId: id
      }
      brandList(params).then(res => {
        this.brandByIdList = res.data
      });
    },
    // 获取商品标签的选择列表
    getSelectList() {
      getSelect().then(res => {
        this.classifyList = res.data
      });
    },
    // 获取区域定价国家选择列表
    getAreaList() {
      getArea().then(res => {
        this.areaList = res.data
      });
    },
    // 获取店铺账号选择列表
    getEmpowerList() {
      queryUserShopList().then(res => {
        this.accountNumber = res.data
      });
    },
    // 判断是否为人民币
    getIsRmb(id) {
      isRmb({sellerId: id}).then(res => {
        this.isRmb = res.data;
        if (this.isRmb) this.isAutoMate = true;
        else this.isAutoMate = false;
      });
    },
    // 获取运费模板选择列表
    getFreightTemplateList(id) {
      listsellerFreightTemplate(id).then(res => {
        this.freightTemplateList = res.data
      });
    },
    // 获取服务模板选择列表
    getPromiseTemplateList(id) {
      listsellerPromiseTemplate(id).then(res => {
        this.serviceTemplateList = res.data
        this.form.promiseTemplateId = res.data[0].value
      });
    },
    // 获取店铺可用营销方案列表
    getStoreActivityList(id) {
      storeActivityList(id).then(res => {
        res.data.forEach(item => {
          // this.$set(item, "label", item.promotionName + '(' + item.existStoreFansDiscount + '%)');
          this.$set(item, "label", item.promotionName);
        })
        this.marketList = res.data
      })
    },
    // 同步运费模板
    freightTemplateSync() {
      if (!this.isAutoMate) {
        this.$confirm('您确定要该操作吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.form.storeId) {
            this.loading = true;
            syncListsellerFreightTemplate(this.form.storeId).then(res => {
              this.$modal.msgSuccess("同步成功");
              this.getFreightTemplateList(this.form.storeId);//获取运费模板
              this.freightTemplateList = res.data
              this.loading = false;
            });
          } else {
            this.$modal.msgError("请选择店铺账号");
          }
        }).catch(() => {
        });
      } else {
        this.$modal.msgError("您已选择自动匹配模板");
      }
    },
    // 同步服务模板
    serviceTemplateSync() {
      this.$confirm('您确定要该操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.form.storeId) {
          this.loading = true;
          syncListsellerPromiseTemplate(this.form.storeId).then(res => {
            this.$modal.msgSuccess("同步成功");
            this.getPromiseTemplateList(this.form.storeId);//获取服务模板
            this.serviceTemplateList = res.data
            this.loading = false;
          });
        } else {
          this.$modal.msgError("请选择店铺账号");
        }
      }).catch(() => {
      });
    },
    // 同步营销方案
    marketSync() {
      this.$confirm('您确定要该操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.form.storeId) {
          this.loading = true;
          selectStorePromotionsTemplate(this.form.storeId).then(res => {
            this.$modal.msgSuccess("同步成功");
            this.getStoreActivityList(this.form.storeId);//获取店铺可用营销方案
            this.marketList = res.data
            this.loading = false;
          });
        } else {
          this.$modal.msgError("请选择店铺账号");
        }
      }).catch(() => {
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: undefined,
        skuStock: undefined,
        freightTemplateId: undefined,
        promiseTemplateId: undefined,
        activityId: undefined,
        priceAdjustmentMethod: '0',
        sellerProductIds: undefined,
        readjustPricesType: '1',
        readjustPrices: undefined,
        templateId: undefined,
        brandId: undefined,
        isAutoMate: '0',
        isAudit: '1',
        reduceStrategy: this.dict.type.erp_reduce_strategy[1].value,
        isMainImageReordering: '2',
        isAddWatemark: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 商品详情编辑提交按钮 */
    submitForm() {
      this.buttonLoading = true;
      var attrRes = [];
      this.detailsForm.customAttributes.forEach(item => {
        var obj = {};
        if (item.attributeShowTypeValue === 'check_box') {
          var values = item.attr_value_id;
          values.forEach(item1 => {
            obj = {};
            obj.attr_name = item.attr_name;
            obj.attr_name_id = item.attr_name_id;
            obj.attr_value = item.attr_value;
            obj.attr_value_id = item1;
            attrRes.push(obj);
          });
        } else {
          obj.attr_name = item.attr_name;
          obj.attr_name_id = item.attr_name_id;
          obj.attr_value = item.attr_value;
          obj.attr_value_id = item.attr_value_id;
          attrRes.push(obj);
        }
      })
      this.detailsForm.customAttributes = JSON.stringify(attrRes);
      updateSellerProduct(this.detailsForm).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.drawer = false;
        this.getList();
      }).finally(() => {
        this.buttonLoading = false;
      });
    },
    // 发布商品到速卖通
    addSellerStoreProductBtn() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.priceAdjustmentMethod == '0' && this.form.readjustPrices || this.form.priceAdjustmentMethod == '1' && this.form.templateId) {
            this.buttonLoading = true;
            if (this.isAutoMate) {
              this.form.isAutoMate = '1';
              this.form.freightTemplateId = ''
            } else {
              this.form.isAutoMate = '0'
            }
            addSellerStoreProduct(this.form).then(response => {
              this.$modal.msgSuccess("发布成功");
              this.open = false
              this.getList();
              this.isIndeterminate = false
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            this.$modal.msgError("请完善产品价格");
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete() {
      // 选中数据
      let proSelect = []
      this.sellerProductList.forEach((item) => {
        if (item.isChecked) {
          proSelect.push(item.id);
        }
      });
      let proSelectIds = proSelect.join(",");
      this.$modal.confirm('是否确认删除卖家商品编号为"' + proSelectIds + '"的数据项？').then(() => {
        this.loading = true;
        return delSellerProduct(proSelectIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    //当点击全选的时候
    onCheckAll(checked) {
      const flag = checked;
      if (flag) {
        this.multiple = false
        this.sellerProductList.forEach((item) => {
          item.isChecked = true;
        });
      } else {
        this.multiple = true
        this.sellerProductList.forEach((item) => {
          item.isChecked = false;
        });
      }
      this.isIndeterminate = false
    },
    //当点击单个选中的时候
    onItemChange(checked, val) {
      const flag = checked;
      var isAll = true;
      let proSelect = []
      this.sellerProductList.forEach((item) => {
        if (item.id == val.id) {
          if (flag) {
            item.isChecked = true;
          } else {
            item.isChecked = false;
          }
        }
        if (item.isChecked == false) {
          isAll = false;
        }
      });
      this.isCheckAll = isAll;
      this.sellerProductList.forEach((item) => {
        if (item.isChecked) {
          proSelect.push(item.id);
        }
      });
      this.multiple = !proSelect.length
      this.isIndeterminate = proSelect.length > 0 && proSelect.length < this.sellerProductList.length;
    },
    // 发布速卖通
    publishBtn() {
      this.reset();
      // 选中数据
      let proSelect = []
      this.proArr = []
      this.sellerProductList.forEach((item) => {
        if (item.isChecked) {
          this.proArr.push(item)
          proSelect.push(item.id);
        }
      });
      if (proSelect.length < 1) {
        return this.$message({
          message: '请选择',
          type: 'warning'
        });
      }
      this.form.sellerProductIds = proSelect.join(",");
      // this.getFreightTemplateList();
      // this.getPromiseTemplateList();
      this.open = true;
      this.title = "速卖通产品上传";
    },
    // 打开商品详情弹框
    openProductDrawer(id) {
      this.productId = id
      this.loading = true;
      getSellerProduct(id).then(res => {
        if (res.data.expand) {
          this.detailsForm = res.data
        } else {
          this.detailsForm = {
            ...res.data, 'expand': {
              'brandId': null,
              'skuProperty': '[]',
              'productAttribute': null
            }
          }
        }
        const categoryId = res.data.categoryId
        if (categoryId) {
          this.getCategoryInfo(categoryId);
        }
        if (this.detailsForm.imageURLs) {
          var imageURLs = this.detailsForm.imageURLs.split(';');
          // 过滤掉后缀为.mp4的照片
          imageURLs = imageURLs.filter(item => item.indexOf('.mp4') == -1);
          this.detailsForm.imageURLs = imageURLs.splice(0, 6).join(";");
        }
        if (this.detailsForm.white) {
          var white = this.detailsForm.white.split(';');
          this.detailsForm.white = white.splice(0, 1).toString();
        }
        if (this.detailsForm.marketing) {
          var marketing = this.detailsForm.marketing.split(';');
          this.detailsForm.marketing = marketing.splice(0, 1).toString();
        }
        this.customAttributes = JSON.parse(res.data.customAttributes || '[]')
        if (res.data.expand && res.data.expand.classifyLabel) {
          const classifyValue = res.data.expand.classifyLabel.split(',');
          const arr = this.classifyList;
          arr.forEach(item => {
            classifyValue.forEach(chirldItem => {
              if (item.value == chirldItem) {
                this.newClassifyList.push(item);
              }
            })
          })
        } else {
          this.newClassifyList = []
        }
        this.loading = false;
        this.drawer = true
      });
    },
    // 获取商品属性
    getCategoryInfo(id) {
      categoryInfo(id).then(res => {
        var resMap = new Map();
        res.data.forEach(item => {
          var attribute = {
            'attr_name_id': item.attr_name_id,
            'attr_name': item.attr_name,
            'zhName': item.zhName || item.attr_name,
            'attr_value_id': item.attr_value_id,
            'attr_value': item.attr_value,
            'values': item.values,
            'attributeShowTypeValue': item.attributeShowTypeValue,
            'required': item.required
          };
          resMap.set(item.attr_name_id, attribute);
        })
        var attrOther = [];
        const customAttributes = Array.isArray(this.detailsForm.customAttributes) ? this.detailsForm.customAttributes : JSON.parse(this.detailsForm.customAttributes || '[]');
        customAttributes.forEach(item => {
          if (item.attr_name_id != 2) {
            if (item.attr_name_id == -1) {
              if (item.attr_name != '' && item.attr_name != undefined) {
                item.zhName = item.attr_name;
                item.attr_value_id = -1;
                item.values = undefined;
                item.attributeShowTypeValue = 'input';
                item.required = '0';
                attrOther.push(item);
              }
            } else {
              var attribute = resMap.get(item.attr_name_id);
              if (attribute == undefined) {
                attribute = {
                  'attr_name_id': -1,
                  'attr_name': item.attr_name,
                  'zhName': item.attr_name,
                  'attr_value_id': -1,
                  'attr_value': item.attr_value,
                  'values': [],
                  'attributeShowTypeValue': 'input',
                  'required': 0
                };
                resMap.set(item.attr_name_id, attribute);
              } else {
                if (item.attr_value_id != -1) {
                  // 获取是否有值
                  if (attribute.attributeShowTypeValue == 'check_box') {
                    var attr_value_id = attribute.attr_value_id;
                    if (attr_value_id == undefined) {
                      attribute.attr_value_id = [item.attr_value_id];
                    } else {
                      attribute.attr_value_id.push(item.attr_value_id);
                    }
                  } else {
                    attribute.attr_value_id = item.attr_value_id;
                    attribute.attr_value = item.attr_value;
                  }
                }
              }
            }
          }
        });
        var attr = [];
        resMap.forEach((key, val) => {
          attr.push(key);
        });
        attr.sort((a, b) => Number(b.required) - Number(a.required));
        attr = [...attr, ...attrOther];
        this.$set(this.detailsForm, 'customAttributes', attr);
      });
    },
    // 关闭商品详情弹框
    handleClose() {
      this.drawer = false;
    },
    // 删除属性值
    attributeDelete(index) {
      this.customAttributes.splice(index, 1)
    },
    // 添加属性值
    attributeDeleteAdd() {
      this.customAttributes.push({
        attr_name: '',
        attr_value: '',
        attr_name_id: '-1'
      })
    },
    // sku列表
    getRowData(ids) {
      const idsArr = ids.split(',').filter(item => !!item)
      const item = this.detailsForm.skuList.filter(item => {
        const skuPropertyIds = item.skuPropertyIds.split(';').filter(item => !!item)
        return ArrayIsSame(skuPropertyIds, idsArr)
      })[0]
      if (item) {
        item.uid = item.id
        return item
      } else {
        return {
          uid: uuid(),
          collectSkuPrice: null,
          skuImage: null,
          skuPrice: null,
          skuStock: null,
          skuLength: null,
          skuHeight: null,
          skuWidth: null,
          skuPropertyIds: ids.toString()
        }
      }
    },
    handleClick(tab, event) {
      this.orderParams.status = tab.$options.propsData.name;
      this.orderParams.pageNum = 1;
      this.getOrderList();
    },
    // 日志
    getOrderList() {
      this.orderLoading = true;
      myPublishingList(this.orderParams).then(res => {
        this.orderLoading = false;
        this.orderLogList = res.rows;
        this.orderTotal = res.total;
      })
    },
    // 查看刊登日志
    handleView() {
      this.orderParams.pageNum = 1;
      this.getOrderList();
      this.isShowOrderLog = true;
    },
    // 生成分享码
    getProductShareCode() {
      this.$prompt('请输入分享码别名', '提示', {
        // inputPattern: /^.+$/,
        // inputErrorMessage: '请输入备注内容',
        // inputValue: inputValue
      }).then((value) => {
        // console.log('valueee', value)
        if (value) {
          // this.$confirm('是否确定设定该订单备注？', '提示').then(() => {
          let proSelect = []
          this.sellerProductList.forEach((item) => {
            if (item.isChecked) {
              proSelect.push(item.id);
            }
          });
          let proSelectIds = proSelect.join(",");
          let data = {
            shareName: value.value,
            products: proSelectIds
          }
          sellerProductShare(data).then(res => {
            this.$message.success(res.msg)
          })
          // })
        }
      })
    },
    //   使用分享码
    queryUseShareCode() {
      this.$prompt('请输入分享码', '提示', {
        // inputPattern: /^.+$/,
        inputErrorMessage: '请输入分享码',
        // inputValue: inputValue
      }).then((value) => {
        if (value) {
          let data = {
            shareCode: value.value,
          }
          useShareCode(data).then(res => {
            this.$message.success(res.msg)
            this.getList()
          })
        }
      })
    },
    // 打开分享码列表弹窗
    openShareCodeModal() {
      queryshareCodeList().then(res => {
        this.shareCodeList = res.rows
        this.isOpenShareCodeModal = true
      })
    },
    //   关闭我的分享码列表
    closeShareCodeModal() {
      this.isOpenShareCodeModal = false
    }
  }
};

// 相同sku比较
function ArrayIsSame(_arr1, _arr2) {
  const arr1 = [..._arr1]
  const arr2 = [..._arr2]
  // 长度比较
  if (arr1.length !== arr2.length) return false
  // 项比较
  while (arr1.length > 0) {
    if (arr2.includes(arr1[0])) {
      const index = arr2.indexOf(arr1[0])
      arr1.splice(0, 1)
      arr2.splice(index, 1)
    } else {
      return false
    }
  }
  return true
}

// 商品规格包装数据
function skuPropertyPackage(skuProperty, index = 0) {
  const ids = [];
  (skuProperty[index] || []).forEach(item => {
    const _ids = [];
    const otherIds = skuPropertyPackage(skuProperty, index + 1)
    if (otherIds.length) {
      _ids.push(...otherIds.map(child => `${item},${child}`))
    } else {
      _ids.push(item)
    }
    ids.push(..._ids)
  })
  return ids
}

</script>

<style lang="scss">
.operation {
  border-top: 1px solid #DFDFDF;
  border-bottom: 1px solid #DFDFDF;
  padding: 10px 0;
  margin: 20px 0;
  display: flex;
  align-items: center;

  .operation-item {
    position: relative;
    font-size: 14px;
    text-align: center;

    &:before {
      content: '';
      width: 1px;
      height: 16px;
      background-color: #DFDFDF;
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -8px;
    }

    .el-icon-upload2 {
      color: #FF6A07;
    }

    .active {
      color: #FF6A07;
    }

    div {
      cursor: pointer;
    }
  }
}

.sellerproduct-list {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .sellerproduct-list-item {
    width: calc((100% - 60px) / 6);
    margin: 0 5px 10px 5px;
    cursor: pointer;

    .pCheckbox {
      width: 100%;

      .el-checkbox {
        width: 100%;
        position: relative;

        .el-checkbox__input {
          position: absolute;
          top: 2px;
          right: 2px;
        }

        .el-checkbox__label {
          padding: 0;
          display: block;
          line-height: normal;

          .sellerproduct-list-item-image {
            width: 100%;
            height: 248px;
            object-fit: cover;
            border: 1px solid #999999;
          }
        }
      }
    }

    .sellerproduct-list-item-info {
      margin: 0 -5px;
      padding: 10px 0 0;

      .info-price {
        font-size: 16px;
        line-height: 20px;
        height: 20px;
        color: #1890ff;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        display: block;
      }

      .info-title {
        font-size: 12px;
        line-height: 16px;
        color: #999999;
        margin-top: 5px;
        display: -webkit-box;
        -webkit-line-clamp: 4;
        -webkit-box-orient: vertical;
        overflow: hidden;
        height: 64px;
      }

      .info-brandName {
        font-size: 12px;
        line-height: 16px;
        color: #999999;
        margin-top: 5px;
        height: 28px;
      }
    }

    .el-card__body {
      padding: 0;
    }
  }
}

.el-dialog__body {
  padding: 20px;

  .form-box {
    width: 100%;
    border: 1px solid #DFDFDF;
    border-radius: 5px;

    .form-box-header {
      background: #f2f2f2;
      padding: 10px;
      border-bottom: 1px solid #DFDFDF;
    }

    .form-box-content {
      padding: 10px;

      .item-flex-box {
        display: flex;
        align-items: center;

        .item-flex-box-input {
          flex: 1;
          padding: 0 20px;

          .item-flex-box-input-i {
            display: flex;
            align-items: center;
          }
        }
      }

      .widthBox {
        .el-select {
          width: 50%;
        }
      }
    }
  }
}

.width-select-1 {
  width: 120px;
}

.width-select-2 {
  width: 200px;
}

.width-input {
  width: 200px;
}

.text {
  display: block;
  font-size: 12px;
  padding: 0 10px;
}

.color {
  color: #1890ff;
  cursor: pointer;
}

.title {
  margin: 5px 0 25px 0px;
  padding: 5px 15px;
  background-color: #f6f6f6 !important;
  line-height: 40px;
  font-size: 14px;
  text-align: left;
}

.paddingLeft-box {
  padding-left: 100px;
  width: 100%;
  margin-bottom: 22px;
}

.flexbox {
  width: 100%;
  display: flex !important;

  .el-form-item__content {
    flex: 1;
  }
}

.flex {
  .el-form-item__content {
    flex: 1;
    display: flex;
    align-items: center;

    .el-input {
      width: 80px;
    }
  }

  .span {
    font-size: 12px;
    line-height: 36px;
    color: #999999;
    padding: 0 10px;
  }
}

.showBox {
  .showBox-item {
    width: 100%;
    padding-bottom: 20px;
  }

  .showBox-button {
    display: flex;
    padding: 0 15px 20px;
  }
}

.tagBox {
  .tagBox-item {
    .tagBox-item-name {
      display: flex;
      align-items: center;

      .name-text {
        line-height: 26px;
        display: block;
      }

      .noneBorder {
        border: none;
        margin-left: 10px;
      }
    }
  }

  .el-tag {
    margin-right: 10px;
  }

  .button-new-tag {
    margin-right: 0px;
  }

  .input-new-tag {
    width: 90px;
    margin-right: 10px;
    vertical-align: bottom;
  }
}

.border-box {
  border: 1px solid #EBEEF5;
  width: 100%;
  padding: 20px;

  .title {
    margin: 0 0 10px;
  }

  .box-input-item {
    display: flex;
    // justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .el-input {
      width: 45%;
    }

    .el-select {
      width: 45%;

      .el-input {
        width: 100%;
      }
    }

    span {
      font-size: 14px;
      line-height: 36px;
      color: #999999;
      cursor: pointer;

      &:hover {
        color: #1890ff;
      }
    }
  }
}

.box-flex {
  padding-top: 30px;

  .el-form-item {
    margin-bottom: 0;
  }
}

.text-input {
  display: block;
  margin-bottom: 22px;

  .span {
    font-size: 12px;
    line-height: 36px;
    color: #999999;
    padding-left: 10px;
  }

  .el-checkbox {
    display: flex;
    align-items: center;

    .el-checkbox__input {
      padding: 0;
    }

    .el-checkbox__label {
      font-size: 12px;
      line-height: 36px;
      color: #999999;
      padding-left: 10px;
    }
  }
}

.check-box-title {
  margin-left: 80px;
  margin-bottom: 10px;
  margin-top: -10px;
}

.check-box {
  width: 55%;
  margin-left: 80px;
  margin-bottom: 30px;
  border: 1px solid #DCDFE6;
  padding: 10px;
  font-size: 12px;
  line-height: 36px;
  color: #999999;

  span {
    padding: 0 5px;
  }
}

.cell {
  .el-form-item {
    margin: 0;
  }
}

.el-drawer__body {
  overflow: hidden;

  .demo-drawer__content {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-form {
      overflow: auto;
      flex: 1;
    }

    .demo-drawer__footer {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px 0;
      border-top: 1px solid #DCDFE6;
    }
  }
}
</style>
